package com.sparrow.socket.tcp.api;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NettyRuntime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;

/**
 * tcp服务
 */
public class TcpServer implements DisposableBean {

    private static Logger logger = LoggerFactory.getLogger(TcpServer.class);

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap bootstrap;
    private ChannelFuture channelFuture;

    private ChannelInitializer<?> channelInitializer;

    private static final int DEFAULT_EVENT_LOOP_THREADS;

    static {
        DEFAULT_EVENT_LOOP_THREADS = NettyRuntime.availableProcessors() * 2;
    }

    public void start(int port) {
        bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(DEFAULT_EVENT_LOOP_THREADS);
        try {
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
            //这个是服务器连接的日志  如果更关注channel active 和 inactive 应该在childHandler里面加loggingHandler
            bootstrap.handler(new LoggingHandler());
            bootstrap.childHandler(channelInitializer);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            //每个子通道(客户端连接)的 SocketChannel 关闭nagle算法
            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
            bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            //高低水位 channel.isWritable() 判断是否可写,防止OOM
            bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(32 * 1024, 64 * 1024));
            channelFuture = bootstrap.bind(port).sync();
            logger.info("[{}] TCP server started on port {}", this.getClass().getSimpleName(), port);
            onBindSuc(channelFuture);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.exit(1);
        }
    }

    protected void onBindSuc(ChannelFuture channelFuture) {

    }

    public void shutdown() {
        try {
            if (channelFuture != null && channelFuture.channel().isOpen()) {
                channelFuture.channel().close().sync();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            workerGroup.shutdownGracefully().get();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        try {
            bossGroup.shutdownGracefully().get();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        logger.info("Class:{} Server 关闭", this.getClass().getSimpleName());
    }

    public void setChannelInitializer(ChannelInitializer<?> channelInitializer) {
        this.channelInitializer = channelInitializer;
    }

    @Override
    public void destroy() throws Exception {
        shutdown();
    }
}
